package com.guguskins.back.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guguskins.back.entity.GuCategory;
import com.guguskins.back.entity.bo.SaveCategoryBo;
import com.guguskins.back.entity.vo.PageVo;
import com.guguskins.back.entity.vo.ResultVo;
import com.guguskins.back.service.GuCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 分类 前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-05-14
 */
@RestController
@RequestMapping("/category")
public class GuCategoryController {

    @Autowired
    private GuCategoryService categoryService;

    @GetMapping("/back/page")
    public ResultVo backPage(@RequestParam(value = "p", required = false, defaultValue = "1") int p,
                             @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        PageVo<GuCategory> categoryPageVo = categoryService.backPage(p, size);
        return ResultVo.success(categoryPageVo);
    }

    @PostMapping("/back/add")
    public ResultVo backAdd(@RequestBody @Validated SaveCategoryBo saveCategoryBo) {
        if (categoryService.backAdd(saveCategoryBo)) {
            return ResultVo.success("添加成功");
        }
        return ResultVo.fail("添加失败");
    }

    @PostMapping("/back/edit")
    public ResultVo backEdit(@RequestBody SaveCategoryBo saveCategoryBo) {
        if (categoryService.backEdit(saveCategoryBo)) {
            return ResultVo.success("修改成功");
        }
        return ResultVo.fail("修改失败");
    }

    @GetMapping("/back/list")
    public ResultVo backList() {
        List<GuCategory> categories = categoryService.list(new LambdaQueryWrapper<GuCategory>(){
            {
                orderByAsc(GuCategory::getCategorySort);
            }
        });
        return ResultVo.success(CollectionUtils.isEmpty(categories) ? new ArrayList<>() : categories);
    }

    /**
     * 首页数据
     */
    @GetMapping("/indexData")
    public ResultVo indexData() {
        List<GuCategory> categories = categoryService.indexData();
        return ResultVo.success(categories);
    }

}
